package com.ruoyi.tb.lmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tb.lmt.domain.vo.TbLmtrepairWorkdetailVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.tb.lmt.domain.bo.TbEquipmentApplyBo;
import com.ruoyi.tb.lmt.domain.vo.TbEquipmentApplyVo;
import com.ruoyi.tb.lmt.domain.TbEquipmentApply;
import com.ruoyi.tb.lmt.mapper.TbEquipmentApplyMapper;
import com.ruoyi.tb.lmt.service.ITbEquipmentApplyService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 大部件申请Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class TbEquipmentApplyServiceImpl implements ITbEquipmentApplyService {

    private final TbEquipmentApplyMapper baseMapper;

    @Autowired
    private TbEquipmentApplyMapper tbEquipmentApplyMapper;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询大部件申请
     */
    @Override
    public TbEquipmentApplyVo queryById(Long ID){
        return baseMapper.selectVoById(ID);
    }

    /**
     * 查询大部件申请列表
     */
    @Override
    public TableDataInfo<TbEquipmentApplyVo> queryPageList(TbEquipmentApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbEquipmentApply> lqw = buildQueryWrapper(bo);
        Page<TbEquipmentApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (TbEquipmentApplyVo vo : result.getRecords()) {
            if (StringUtils.isNotBlank(vo.getCreateBy())){
                SysUser sysUser = sysUserService.selectUserByUserName(vo.getCreateBy());
                if (sysUser!=null){
                    vo.setCreateByName(sysUser.getNickName());
                }
            }
            if (StringUtils.isNotBlank(vo.getApprovedBy())){
                SysUser sysUser = sysUserService.selectUserByUserName(vo.getApprovedBy());
                if (sysUser!=null){
                    vo.setApprovedByName(sysUser.getNickName());
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询大部件申请列表
     */
    @Override
    public List<TbEquipmentApplyVo> queryList(TbEquipmentApplyBo bo) {
        LambdaQueryWrapper<TbEquipmentApply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbEquipmentApply> buildQueryWrapper(TbEquipmentApplyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbEquipmentApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLmtNumber()), TbEquipmentApply::getLmtNumber, bo.getLmtNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkGroup()), TbEquipmentApply::getWorkGroup, bo.getWorkGroup());
        lqw.eq(bo.getWorkGroupId() != null, TbEquipmentApply::getWorkGroupId, bo.getWorkGroupId());
        lqw.eq(StringUtils.isNotBlank(bo.getEquipmentCode()), TbEquipmentApply::getEquipmentCode, bo.getEquipmentCode());
        lqw.like(StringUtils.isNotBlank(bo.getEquipmentName()), TbEquipmentApply::getEquipmentName, bo.getEquipmentName());
        lqw.eq(StringUtils.isNotBlank(bo.getLmtLength()), TbEquipmentApply::getLmtLength, bo.getLmtLength());
        lqw.eq(StringUtils.isNotBlank(bo.getAssetsCode()), TbEquipmentApply::getAssetsCode, bo.getAssetsCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOldEquipmentCode()), TbEquipmentApply::getOldEquipmentCode, bo.getOldEquipmentCode());
        lqw.eq(StringUtils.isNotBlank(bo.getEngineTime()), TbEquipmentApply::getEngineTime, bo.getEngineTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTampingNumber()), TbEquipmentApply::getTampingNumber, bo.getTampingNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getHomeworkMileage()), TbEquipmentApply::getHomeworkMileage, bo.getHomeworkMileage());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TbEquipmentApply::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getApprovedBy()), TbEquipmentApply::getApprovedBy, bo.getApprovedBy());
        lqw.eq(StringUtils.isNotBlank(bo.getReason()), TbEquipmentApply::getReason, bo.getReason());
        lqw.eq(bo.getSubmissionTime() != null, TbEquipmentApply::getSubmissionTime, bo.getSubmissionTime());
        lqw.eq(bo.getCreateTime() != null, TbEquipmentApply::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), TbEquipmentApply::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getUpdateTime() != null, TbEquipmentApply::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), TbEquipmentApply::getUpdateBy, bo.getUpdateBy());
        return lqw;
    }

    /**
     * 新增大部件申请
     */
    @Override
    public Boolean insertByBo(TbEquipmentApplyBo bo) {
        TbEquipmentApply add = BeanUtil.toBean(bo, TbEquipmentApply.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setID(add.getID());
        }
        return flag;
    }

    /**
     * 修改大部件申请
     */
    @Override
    public Boolean updateByBo(TbEquipmentApplyBo bo) {
        TbEquipmentApply update = BeanUtil.toBean(bo, TbEquipmentApply.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbEquipmentApply entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除大部件申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TbEquipmentApplyVo selectByCode(String equipmentCode) {
        return tbEquipmentApplyMapper.selectByCode(equipmentCode);
    }

    @Override
    public TableDataInfo<TbEquipmentApplyVo> selectApplyList(PageQuery pageQuery) {

        //获取当前用户内容
        LoginUser loginUser = LoginHelper.getLoginUser();
        String username = loginUser.getUsername();
        Long deptId = loginUser.getDeptId();

        // 检查当前用户的角色
        boolean isAdmin = isAdmin(username); // 是否为管理员
        boolean isDeputyDirector = isDeputyDirector(username); // 是否为车间副主任
        boolean isEquipmentDept = isEquipmentDept(username); // 是否为设备科人员

        // 查询符合条件的大部件申请列表
        List<TbEquipmentApplyVo> result = null;
        if (isAdmin) {
            // 管理员可以看到所有申请列表
            result = tbEquipmentApplyMapper.selectApplyList();
        } else if (isEquipmentDept) {
            // 设备科人员可以看到所有申请列表
            result = tbEquipmentApplyMapper.selectApplyList();
        } else if (isDeputyDirector) {
            // 车间副主任只能看到与其审批相关的申请列表
            result = tbEquipmentApplyMapper.selectApplyListByDeputyDirector(username);
        } else {
            // 其他用户只能看到自己提交的申请列表
            result = tbEquipmentApplyMapper.selectApplyListByUsername(username);
        }
        //分页
        if (pageQuery.getPageSize() != null && pageQuery.getPageNum() != null) {
            List<TbEquipmentApplyVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), result);
            TableDataInfo res = new TableDataInfo<>(page, result.size());
            return res;
        } else {
            return TableDataInfo.build(result);
        }
    }

    public boolean isAdmin(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有管理员的角色标识
        for (SysRole role : userRoles) {
            if ("admin".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
    public boolean isEquipmentDept(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有设备科的角色标识
        for (SysRole role : userRoles) {
            if ("equipmentDept".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
    public boolean isDeputyDirector(String username) {
        // 通过用户名获取用户的所有角色
        List<SysRole> userRoles = iSysRoleService.selectRolesByUserName(username);

        // 检查用户是否有车间副主任的角色标识
        for (SysRole role : userRoles) {
            if ("deputyDirector".equals(role.getRoleKey())) {
                return true;
            }
        }
        return false;
    }
}
